import 'package:flutter/material.dart';
import '../models/community.dart';
import '../services/community_service.dart';
import '../utils/theme_colors.dart';
import '../widgets/post_card.dart';
import '../widgets/community_filter_sheet.dart';
import 'post_detail_screen.dart';
import 'create_post_screen.dart';

class CommunityScreen extends StatefulWidget {
  const CommunityScreen({Key? key}) : super(key: key);

  @override
  State<CommunityScreen> createState() => _CommunityScreenState();
}

class _CommunityScreenState extends State<CommunityScreen>
    with TickerProviderStateMixin {
  final CommunityService _communityService = CommunityService.instance;
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  
  late TabController _tabController;
  List<Post> _posts = [];
  List<Topic> _topics = [];
  List<CommunityUser> _activeUsers = [];
  bool _isLoading = true;
  String _searchQuery = '';
  PostType? _selectedType;
  String? _selectedTopicId;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 4, vsync: this);
    _loadData();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _searchController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _loadData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      final results = await Future.wait([
        _communityService.getPosts(),
        _communityService.getTopics(),
        _communityService.getActiveUsers(),
      ]);

      if (mounted) {
        setState(() {
          _posts = results[0] as List<Post>;
          _topics = results[1] as List<Topic>;
          _activeUsers = results[2] as List<CommunityUser>;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('加载数据失败: $e')),
        );
      }
    }
  }

  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      // 加载更多数据
      _loadMorePosts();
    }
  }

  Future<void> _loadMorePosts() async {
    // 实现分页加载
  }

  List<Post> get _filteredPosts {
    var filtered = _posts;
    
    if (_searchQuery.isNotEmpty) {
      filtered = filtered.where((post) {
        return post.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
               post.content.toLowerCase().contains(_searchQuery.toLowerCase());
      }).toList();
    }
    
    if (_selectedType != null) {
      filtered = filtered.where((post) => post.type == _selectedType).toList();
    }
    
    if (_selectedTopicId != null) {
      filtered = filtered.where((post) => post.topicId == _selectedTopicId).toList();
    }
    
    return filtered;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: Column(
        children: [
          _buildHeader(),
          _buildTabBar(),
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: [
                _buildPostsTab(),
                _buildTopicsTab(),
                _buildUsersTab(),
                _buildMyTab(),
              ],
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _createPost,
        backgroundColor: ThemeColors.primary,
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              const Text(
                '社区交流',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const Spacer(),
              IconButton(
                onPressed: _showFilterSheet,
                icon: Icon(
                  Icons.filter_list,
                  color: ThemeColors.primary,
                ),
              ),
              IconButton(
                onPressed: () {},
                icon: Icon(
                  Icons.notifications_outlined,
                  color: ThemeColors.primary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          TextField(
            controller: _searchController,
            decoration: InputDecoration(
              hintText: '搜索帖子、话题...',
              prefixIcon: const Icon(Icons.search),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(25),
                borderSide: BorderSide.none,
              ),
              filled: true,
              fillColor: Colors.grey[100],
              contentPadding: const EdgeInsets.symmetric(
                horizontal: 16,
                vertical: 12,
              ),
            ),
            onChanged: (value) {
              setState(() {
                _searchQuery = value;
              });
            },
          ),
        ],
      ),
    );
  }

  Widget _buildTabBar() {
    return Container(
      color: Colors.white,
      child: TabBar(
        controller: _tabController,
        labelColor: ThemeColors.primary,
        unselectedLabelColor: ThemeColors.textSecondary,
        indicatorColor: ThemeColors.primary,
        tabs: const [
          Tab(text: '最新'),
          Tab(text: '话题'),
          Tab(text: '用户'),
          Tab(text: '我的'),
        ],
      ),
    );
  }

  Widget _buildPostsTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    final posts = _filteredPosts;
    
    if (posts.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.forum_outlined,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text(
              '暂无帖子',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: _loadData,
      child: ListView.builder(
        controller: _scrollController,
        padding: const EdgeInsets.all(16),
        itemCount: posts.length,
        itemBuilder: (context, index) {
          final post = posts[index];
          return PostCard(
            post: post,
            onTap: () => _navigateToPostDetail(post),
            onLike: () => _toggleLike(post),
            onComment: () => _navigateToPostDetail(post, scrollToComments: true),
            onShare: () => _sharePost(post),
          );
        },
      ),
    );
  }

  Widget _buildTopicsTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return RefreshIndicator(
      onRefresh: _loadData,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _topics.length,
        itemBuilder: (context, index) {
          final topic = _topics[index];
          return Card(
            margin: const EdgeInsets.only(bottom: 12),
            child: ListTile(
              leading: Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  color: ThemeColors.primary.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  Icons.topic,
                  color: ThemeColors.primary,
                ),
              ),
              title: Text(
                topic.name,
                style: const TextStyle(
                  fontWeight: FontWeight.w600,
                ),
              ),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    topic.description,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: ThemeColors.textSecondary,
                      fontSize: 12,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '${topic.postCount}个帖子 · ${topic.followerCount}人关注',
                    style: TextStyle(
                      color: ThemeColors.textSecondary,
                      fontSize: 11,
                    ),
                  ),
                ],
              ),
              trailing: topic.isFollowing
                  ? TextButton(
                      onPressed: () => _toggleFollowTopic(topic),
                      child: const Text('已关注'),
                    )
                  : OutlinedButton(
                      onPressed: () => _toggleFollowTopic(topic),
                      child: const Text('关注'),
                    ),
              onTap: () => _navigateToTopic(topic),
            ),
          );
        },
      ),
    );
  }

  Widget _buildUsersTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    return RefreshIndicator(
      onRefresh: _loadData,
      child: ListView.builder(
        padding: const EdgeInsets.all(16),
        itemCount: _activeUsers.length,
        itemBuilder: (context, index) {
          final user = _activeUsers[index];
          return Card(
            margin: const EdgeInsets.only(bottom: 12),
            child: ListTile(
              leading: CircleAvatar(
                radius: 25,
                backgroundColor: ThemeColors.primary.withOpacity(0.1),
                child: Text(
                  user.nickname.substring(0, 1),
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    color: ThemeColors.primary,
                  ),
                ),
              ),
              title: Row(
                children: [
                  Text(
                    user.nickname,
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                    decoration: BoxDecoration(
                      color: _getLevelColor(user.level),
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Text(
                      'Lv.${user.level}',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 10,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
              subtitle: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    user.bio,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: ThemeColors.textSecondary,
                      fontSize: 12,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Row(
                    children: [
                      Icon(
                        Icons.article_outlined,
                        size: 14,
                        color: ThemeColors.textSecondary,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        '${user.postCount}帖',
                        style: TextStyle(
                          color: ThemeColors.textSecondary,
                          fontSize: 11,
                        ),
                      ),
                      const SizedBox(width: 12),
                      Icon(
                        Icons.thumb_up_outlined,
                        size: 14,
                        color: ThemeColors.textSecondary,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        '${user.likeCount}赞',
                        style: TextStyle(
                          color: ThemeColors.textSecondary,
                          fontSize: 11,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              trailing: user.isFollowing
                  ? TextButton(
                      onPressed: () => _toggleFollowUser(user),
                      child: const Text('已关注'),
                    )
                  : OutlinedButton(
                      onPressed: () => _toggleFollowUser(user),
                      child: const Text('关注'),
                    ),
              onTap: () => _navigateToUserProfile(user),
            ),
          );
        },
      ),
    );
  }

  Widget _buildMyTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 个人信息卡片
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 30,
                    backgroundColor: ThemeColors.primary.withOpacity(0.1),
                    child: Text(
                      '我',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: ThemeColors.primary,
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '我的昵称',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          '非遗文化爱好者',
                          style: TextStyle(
                            color: ThemeColors.textSecondary,
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: Colors.orange,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Text(
                      'Lv.5',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          
          // 统计信息
          Row(
            children: [
              Expanded(
                child: _buildStatCard('我的帖子', '12', Icons.article_outlined),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildStatCard('获得点赞', '89', Icons.thumb_up_outlined),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildStatCard('关注话题', '6', Icons.topic_outlined),
              ),
            ],
          ),
          const SizedBox(height: 16),
          
          // 功能列表
          Card(
            child: Column(
              children: [
                _buildMenuItem(Icons.bookmark_outline, '我的收藏', () {}),
                _buildMenuItem(Icons.history, '浏览历史', () {}),
                _buildMenuItem(Icons.people_outline, '我的关注', () {}),
                _buildMenuItem(Icons.settings_outlined, '设置', () {}),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String title, String value, IconData icon) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Icon(
              icon,
              size: 24,
              color: ThemeColors.primary,
            ),
            const SizedBox(height: 8),
            Text(
              value,
              style: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              title,
              style: TextStyle(
                color: ThemeColors.textSecondary,
                fontSize: 12,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMenuItem(IconData icon, String title, VoidCallback onTap) {
    return ListTile(
      leading: Icon(icon, color: ThemeColors.primary),
      title: Text(title),
      trailing: const Icon(Icons.chevron_right),
      onTap: onTap,
    );
  }

  Color _getLevelColor(int level) {
    if (level >= 10) return Colors.purple;
    if (level >= 7) return Colors.red;
    if (level >= 4) return Colors.orange;
    return Colors.green;
  }

  void _showFilterSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => CommunityFilterSheet(
        selectedType: _selectedType,
        selectedTopicId: _selectedTopicId,
        onFilterChanged: (type, topicId) {
          setState(() {
            _selectedType = type;
            _selectedTopicId = topicId;
          });
        },
      ),
    );
  }

  void _createPost() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => const CreatePostScreen(),
      ),
    ).then((result) {
      if (result == true) {
        _loadData();
      }
    });
  }

  void _navigateToPostDetail(Post post, {bool scrollToComments = false}) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PostDetailScreen(
          postId: post.id,
          scrollToComments: scrollToComments,
        ),
      ),
    );
  }

  Future<void> _toggleLike(Post post) async {
    try {
      if (post.isLiked) {
        await _communityService.unlikePost(post.id);
      } else {
        await _communityService.likePost(post.id);
      }
      _loadData();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    }
  }

  void _sharePost(Post post) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('分享功能开发中...')),
    );
  }

  void _navigateToTopic(Topic topic) {
    // 跳转到话题详情页面
  }

  Future<void> _toggleFollowTopic(Topic topic) async {
    try {
      if (topic.isFollowing) {
        await _communityService.unfollowTopic(topic.id);
      } else {
        await _communityService.followTopic(topic.id);
      }
      _loadData();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    }
  }

  void _navigateToUserProfile(CommunityUser user) {
    // 跳转到用户详情页面
  }

  Future<void> _toggleFollowUser(CommunityUser user) async {
    try {
      if (user.isFollowing) {
        await _communityService.unfollowUser(user.id);
      } else {
        await _communityService.followUser(user.id);
      }
      _loadData();
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('操作失败: $e')),
      );
    }
  }
}